package view;

import model.Product;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.NumberFormat;

public class DialogProductMod extends JDialog {

    private final static int INIT_W = 250;  //窗体初始宽度
    private final static int INIT_H = 300;  //窗体初始高度

    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextField tf_productId;
    private JTextField tf_productName;
    private JTextField tf_category;
    private JFormattedTextField tf_sellingPrice;
    private JTextField tf_purchasePrice;

    WarehousePane warehousePane;

    private void createUIComponents() {
        //输入字符限制
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        tf_sellingPrice = new JFormattedTextField(nf);
    }

    public DialogProductMod(WarehousePane warehousePane, Product oldProduct) {
        this.warehousePane = warehousePane;

        setTitle("修改商品信息");
        setSize(INIT_W,INIT_H);
        setResizable(false);
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);
        //居中
        Point p = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
        setBounds(p.x - INIT_W / 2, p.y - INIT_H / 2, INIT_W, INIT_H);
        //旧数值

        tf_productId.setText(String.valueOf(oldProduct.getProductId()));
        tf_productName.setText(oldProduct.getProductName());
        tf_category.setText(oldProduct.getCategory());
        tf_sellingPrice.setText(String.valueOf(oldProduct.getSellingPrice()));
        tf_purchasePrice.setText(String.valueOf(oldProduct.getPurchasePrice()));

        buttonOK.addActionListener(e -> onOK());

        buttonCancel.addActionListener(e -> onCancel());

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(
                e -> onCancel(),
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void onOK() {
        Product newProductInfo = getProductInfo();
        if (newProductInfo != null) {
            if (Product.modProduct(newProductInfo)) {
                JOptionPane.showMessageDialog(this, "商品修改成功", "修改商品", JOptionPane.INFORMATION_MESSAGE);
                warehousePane.notifyProductDataChanged();
                dispose();
            }
            else {
                JOptionPane.showMessageDialog(this, "商品修改失败", "修改商品", JOptionPane.ERROR_MESSAGE);
            }
        }
        else {
            JOptionPane.showMessageDialog(this, "商品修改失败，信息不能为空", "修改商品", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void onCancel() {
        // add your code here if necessary
        dispose();
    }

    //从输入框获取商品信息
    private Product getProductInfo() {
        String str_id = tf_productId.getText();
        String str_name = tf_productName.getText();
        String str_category = tf_category.getText();
        String str_sell = tf_sellingPrice.getText();

        try {
            if (str_id != null && !str_id.isBlank() && str_name != null && !str_name.isBlank() &&
                    str_category != null && !str_category.isBlank() && str_sell != null && !str_sell.isBlank()) {
                return new Product(
                        Integer.parseInt(str_id),
                        str_name,
                        str_category,
                        Float.parseFloat(str_sell)
                );
            }
            else{
                JOptionPane.showMessageDialog(contentPane, "请输入正确数值(大于0的整数)", null, JOptionPane.ERROR_MESSAGE);
            }
        } catch (NumberFormatException exception) {
            JOptionPane.showMessageDialog(contentPane, "请输入正确数值(大于0的整数)", null, JOptionPane.ERROR_MESSAGE);

        }
        return null;
    }
}
